package com.yumeng.framework.auth.shiro.realm;

import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.service.TokenService;
import com.yumeng.framework.auth.shiro.token.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author wxd
 * @date 2022/4/13 9:31
 */
@Slf4j
public class JwtRealm extends AuthorizingRealm {

    public static final String DEFAULT_BEAN_NAME = "jwtRealm";

    private final TokenService tokenService;

    public JwtRealm(TokenService tokenService){
        setName("jwtRealm");
        setAuthenticationCachingEnabled(false);
        setAuthorizationCachingEnabled(false);
        this.tokenService = tokenService;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.debug("JwtRealm::授权");
        return null;//返回null，且不缓存，权限走UsernameRealm
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.debug("JwtRealm::认证");
        //shiro过滤器拦截到请求并获取header中的token，并提交到自定义realm的doGetAuthenticationInfo方法。
        //通过jwt解码获取token中的用户名、用户id，从缓存或数据库中查询用户信息，得到salt，然后提交验证jwt有效性。
        JwtToken jwtToken = (JwtToken)token;
        String jwt = jwtToken.getToken();

        log.debug("JwtRealm::认证，地址：{}", jwtToken.getHost());

        BaseAuthInfo authInfo = tokenService.getAuthInfoByToken(jwt, true);

        //TODO 状态判断 应该不放在这  放在tokenService.getAuthInfoByToken中？

        return new SimpleAuthenticationInfo(authInfo, authInfo.getSalt(), getName());
    }

}
